<template>
  <div>
    <div class="search-term">
      <el-form :inline="true" :model="searchInfo" class="demo-form-inline">
        <el-form-item label="字典名称">
          <el-input placeholder="搜索条件" v-model="searchInfo.dict_name" clearable></el-input>
        </el-form-item>
        <el-form-item label="字典类型">
          <el-input placeholder="搜索条件" v-model="searchInfo.dict_code" clearable></el-input>
        </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-select v-model="searchInfo.status" clearable placeholder="请选择">
                <el-option
                        v-for="dict in statusOptions"
                        :key="dict.item_value"
                        :label="dict.item_name"
                        :value="dict.item_value"
                />
              </el-select>
            </el-form-item>
        <el-form-item>
          <el-button @click="handleQuery" icon="el-icon-search" type="primary">查询</el-button>
        </el-form-item>
      </el-form>
      <el-form>
        <el-form-item>
          <el-button @click="createSysDictionary" type="primary">新增字典</el-button>
          <el-button @click="refreshDictStorage" type="success">刷新生效</el-button>
        </el-form-item>

      </el-form>
    </div>
    <el-table
      :data="tableData"
      border
      ref="multipleTable"
      row-key="ID"
      stripe
      style="width: 100%"
      tooltip-effect="dark"
    >
    <el-table-column label="ID" width="50" prop="ID">
         <template slot-scope="scope">{{scope.row.ID}}</template>
    </el-table-column>

    <el-table-column label="字典名称" prop="dict_name" width="120"></el-table-column>
    <el-table-column label="字典类型" align="center" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <router-link :to="{name: 'dictionaryDetail', params:{id:scope.row.dict_code}}" class="link-type">
                <span>{{ scope.row.dict_code }}</span>
              </router-link>
            </template>
    </el-table-column>
    <el-table-column label="状态" min-width="60">
        <template slot-scope="scope">{{scope.row.status|formatString}}</template>
      </el-table-column>
    <el-table-column label="备注" prop="dict_desc" width="180"></el-table-column>
    <el-table-column label="创建时间" width="340">
         <template slot-scope="scope">{{scope.row.CreatedAt|formatDate}}</template>
    </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button @click="updateSysDictionary(scope.row)" icon="el-icon-edit" size="small" type="primary">编辑</el-button>
          <el-button @click="deleteSysDictionary(scope.row)" type="danger" icon="el-icon-delete" style="margin-left: 6px;" size="mini" >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      :current-page="page"
      :page-size="pageSize"
      :page-sizes="[10, 30, 50, 100]"
      :style="{float:'right',padding:'20px'}"
      :total="total"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
      layout="total, sizes, prev, pager, next, jumper"
    ></el-pagination>

    <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible" width="600px" >
      <el-form ref="elForm" :model="formData" :rules="rules" size="medium" label-width="110px">
      <el-form-item label="字典名称" prop="dict_name">
        <el-input v-model="formData.dict_name" placeholder="请输入字典名称" clearable :style="{width: '90%'}"></el-input>
      </el-form-item>
      <el-form-item label="字典类型" prop="dict_code">
        <el-input v-model="formData.dict_code" placeholder="请输入字典类型" clearable :style="{width: '90%'}"></el-input>
      </el-form-item>
      <el-form-item label="状态" prop="status" required>
        <el-radio-group v-model="formData.status">
          <el-radio
                  v-for="dict in statusOptions"
                  :key="dict.item_value"
                  :label="dict.item_value |formatBoolean"
          >{{ dict.item_name }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="备注" prop="dict_desc">
        <el-input v-model="formData.dict_desc" placeholder="请输入备注" clearable type="textarea" :style="{width: '90%'}"></el-input>
      </el-form-item>
    </el-form>

      <div class="dialog-footer" slot="footer">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button @click="enterDialog" type="primary">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
    createSysDictionary,
    deleteSysDictionary,
    updateSysDictionary,
    getSysDictionaryList
} from "@/api/sysDictionary";  //  此处请自行替换地址
import { formatTimeToStr } from "@/utils/date";
import infoList from "@/mixins/infoList";
export default {
  name: "SysDictionary",
  mixins: [infoList],
  data() {
    return {
      statusOptions: [],
      listApi: getSysDictionaryList,
      dialogFormVisible: false,
      dialogTitle: "新增字典",
      dialogType: "add",
      visible: false,
      searchInfo: {
        dict_name: undefined,
        dict_code: undefined,
        status: undefined
      },
      type: "",
      formData: {
        name:null,type:null,status:true,desc:null
      },
      rules: {
        name: [{
          required: true,
          message: '请输入字典名（中）',
          trigger: 'blur'
        }],
        type: [{
          required: true,
          message: '请输入字典名（英）',
          trigger: 'blur'
        }],
        desc: [{
          required: true,
          message: '请输入描述',
          trigger: 'blur'
        }],
      },
    };
  },
  filters: {
    formatDate: function(time) {
      if (time != null && time != "") {
        var date = new Date(time);
        return formatTimeToStr(date, "yyyy-MM-dd hh:mm:ss");
      } else {
        return "";
      }
    },
    formatString: function(bool) {
      if (bool != null) {
        return bool ? "正常" :"关闭";
      } else {
        return "";
      }
    },
    formatBoolean: function(s) {
      if (s == "1" ) {
        return true
      } else {
        return false;
      }
    }
  },
  methods: {
      //条件搜索前端看此方法
    handleQuery() {
        if (this.searchInfo.status==""){
          this.searchInfo.status=null
        }
        this.getTableData()
      },
    async updateSysDictionary(row) {
      this.type = "update";
      this.formData = row;
      this.dialogTitle = '编辑字典'
      this.dialogFormVisible = true;

    },
    async createSysDictionary() {
      this.formData = {
        name:null,type:null,status:true,desc:null
      };
      this.type = "create";
      this.dialogFormVisible = true;
      this.dialogTitle = '新增字典';
    },
    closeDialog() {
      this.dialogFormVisible = false;
      this.formData = {
          name:null,
          type:null,
          status:true,
          desc:null,
      };
    },
    // 删除角色
    deleteSysDictionary(row) {
      this.$confirm("此操作将永久删除该字典, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
              .then(async () => {
                this.visible = false;
                const res = await deleteSysDictionary({ ID: row.ID });
                if (res.code == 0) {
                  this.$message({
                    type: "success",
                    message: "删除成功!"
                  });
                  await this.getTableData();
                }
              })
              .catch(() => {
                this.$message({
                  type: "info",
                  message: "已取消删除"
                });
              });
    },
    async enterDialog() {
      this.$refs['elForm'].validate(async valid => {
        if (!valid) return
        let res;
        switch (this.type) {
          case "create":
            res = await createSysDictionary(this.formData);
            break;
          case "update":
            res = await updateSysDictionary(this.formData);
            break;
          default:
            res = await createSysDictionary(this.formData);
            break;
        }
         if (res.code == 0) {
        this.closeDialog();
        await this.getTableData();
      }
      })
    },
    refreshDictStorage() {
      console.log('refreshDictStorage')
      // 强制刷新将字典 dictionaryList放入 localStorage
      getSysDictionaryList({'page': 1, 'pageSize': 100}).then(
        response => {
          localStorage.setItem('dictionaryList', JSON.stringify(response.data.list))
        })
    }
  },
  async created() {
    await this.getTableData();
    this.statusOptions = this.getDicItemList('sys_common_status');
  }
};
</script>

<style type="text/css" scoped="scoped">
  .link-type, .link-type:focus {
    color: #337ab7;
    cursor: pointer;
  }
</style>
